package org.xbdframework.boot.autoconfigure.jdbc;

import javax.sql.DataSource;

import org.xbdframework.boot.autoconfigure.dao.DaoAutoConfiguration;
import org.xbdframework.jdbc.core.support.JdbcDaoBeanPostProcessor;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

/**
 * Jdbc-Based 相关自动化配置
 * @author luas
 * @since 1.5.0
 */
@Configuration
@ConditionalOnClass({ DataSource.class, JdbcDaoBeanPostProcessor.class })
@ConditionalOnSingleCandidate(DataSource.class)
@AutoConfigureBefore({ DaoAutoConfiguration.class })
@AutoConfigureAfter({ JdbcTemplateAutoConfiguration.class })
public class JdbcAutoConfiguration {

    /**
     * 随Spring Boot自动判断并初始化{@code JdbcDaoBeanPostProcessor}.
     * <p>此类会判断系统是否依赖了xbd-dao，如没有依赖，则创建{@code JdbcDaoBeanPostProcessor}实例.
     */
    @Configuration
    @ConditionalOnMissingClass("org.xbdframework.dao.core.support.XbdJdbcDaoBeanPostProcessor")
    public static class JdbcDaoConfiguration {

        private final JdbcTemplate jdbcTemplate;

        private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;

        JdbcDaoConfiguration(JdbcTemplate jdbcTemplate,
                             NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
            this.jdbcTemplate = jdbcTemplate;
            this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
        }

        @Bean
        @ConditionalOnMissingBean(JdbcDaoBeanPostProcessor.class)
        public JdbcDaoBeanPostProcessor jdbcDaoBeanPostProcessor() {
            JdbcDaoBeanPostProcessor jdbcDaoBeanPostProcessor = new JdbcDaoBeanPostProcessor();

            jdbcDaoBeanPostProcessor.setJdbcTemplate(this.jdbcTemplate);
            jdbcDaoBeanPostProcessor.setNamedParameterJdbcTemplate(this.namedParameterJdbcTemplate);

            return jdbcDaoBeanPostProcessor;
        }
    }
}
